<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use App\Http\Controllers\CateTree;

/**
 * 商品分类模型
 */
class Category extends Model
{
    protected $table = 'category';
    public $timestamps = false;
    protected $guarded = [];
    
    /**
     * 获取分类列表
     * @return type
     */
    public static function getList()
    {
        $allcate = self::where('cate_status', '<>', -1)->get()->toArray();
        return CateTree::getList($allcate);
    }
    
    // 获取子孙树
    public static function getTree()
    {
        $allcate = self::where('cate_status', '<>', -1)->get()->toArray();
        return CateTree::getTree($allcate);
    }
    
    // 获取自身及子类id
    public static function getSonsId($pid)
    {
        $lists = self::getList();
        $child = $lists[$pid]['childs'];
        
        if ($child) {
            $ids = $pid . ',' . $child;
        } else {
            $ids = 0 . ',' . $pid;
        }
        
        return $ids;
    }
    
    // 获取导航条
    public static function navs()
    {
        $navs = self::where('cate_isnav', 1)
                ->where('cate_status',1)
                ->orderBy('cate_sort','asc')
                ->limit(8)
                ->get();
        return $navs;
    }
    
    // 获取上级分类ID
    public function getCrumb($id, $self=true)
    {
        $crumb = [];
        // 先获取当前分类的path
        $path = $this->where('id', $id)->pluck('path');
        
        if($path){
            $ids = explode(',', $path);
            $crumb = $this->whereIn('id', $ids)->select(['id','cate_name'])->get();
        }
        
        return $crumb;
    }
}
